import 'dart:async';

import 'package:get/get.dart';
import 'package:star_author/generated/json/base/json_convert_content.dart';
import 'package:star_author/model/shop_title_entity.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/event.dart';
import 'package:star_author/utils/http/api_manager.dart';
import 'package:star_author/utils/http/http_util.dart';

//todo:品类
class CategoryController extends GetxController {
  List all_categories = [];

  CategoryController() {
    LogUtil.v("init_cate");
    initData();
    getCategory();
  }

  //初始化获取所有分类
  getCategory() {
    HttpUtil.commonRequest(
      Get.context!,
      ApiManager.categories,
      isLoading: false,
      isErrorToast: false,
      queryParameters: {
        "all_category": true,
      },
    ).then((value) {
      all_categories = value.data["data"] ?? [];
      Event.emit('refresh_categories');
      update();
    }).catchError((e) {
      LogUtil.v("e;${e.toString()}");
    });
  }

  //区分页面展示
  //参数值:backflow,treasure,store
  List getCategoriesType(String type) {
    return all_categories
        .where(
            (element) => ((element['show_area'] ?? []) as List).contains(type))
        .toList();
  }

  //获取子类目录
  Future<List<ShopTitleChildrenEntity>> getChildren(
    id, {
    type: "store",
  }) async {
    List<ShopTitleChildrenEntity> result = [];
    await HttpUtil.commonRequest(
      Get.context!,
      "/api/v1/categories/${id}/children",
      isLoading: false,
      isErrorToast: false,
    ).then((value) {
      ShopChlildrenEntity? shopChlildrenEntity =
          JsonConvert.fromJsonAsT(value.data);
      result = shopChlildrenEntity?.data ?? [];
    });
    return result;
  }

  //增加一个定时获取后台数据 更新 暂定为一个小时一次
  initData() {
    Timer.periodic(Duration(minutes: 30), (timer) {
      getCategory();
    });
  }
}
